package com.jianda.commons.util;

import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 本地持久化list工具类
 */
//@Slf4j
public class ListSaveUtils {

    /**
     * 持久化list
     * @param list
     */
    public static void saveStorageList(List list, String path) {
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-hhmmss");
        String date = format.format(new Date());
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        String filePath = file1.getPath() +  "//" + date + ".txt";

        try {
            fileOutputStream = new FileOutputStream(filePath);
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(list);
           // log.info("list本地持久化成功，保存路径{}", filePath);
            System.out.println("数据本地保存成功，路径{}" + filePath);
        } catch (Exception e) {
            e.printStackTrace();
        //    log.error("list本地持久化失败{},\\n 原因{}", e.getMessage(), e.getCause());
        } finally {
            try {
                if (fileOutputStream != null)
                    fileOutputStream.close();
                if (objectOutputStream != null)
                    objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取本地的list文件数据
     * @param fileName
     */
    public static   List<Integer> getStorageList(String fileName, String path) {
        ObjectInputStream objectInputStream = null;
        FileInputStream fileInputStream = null;
        List<Integer> list = new ArrayList();
        try {
            String filePath = path +  "//" + fileName;
            fileInputStream = new FileInputStream(filePath);
            objectInputStream = new ObjectInputStream(fileInputStream);
            list = (List) objectInputStream.readObject();
       //     log.info("读取list数据成功, 读取路径{}", filePath);
            return list;
        } catch (Exception e) {
         //   log.error("读取本地文件{}失败", fileName);
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
                if (objectInputStream != null) {
                    objectInputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("获取本地文件时发生IO异常");
            }
        }
        return null;
    }
}
